import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { Button, Table, TableBody, TableCell, TableHead,  TableRow, TableSortLabel,  Paper, Divider, Tooltip, Menu, MenuItem } from '@material-ui/core';

import styled from 'styled-components';
import axios from 'axios';
import swal from 'sweetalert2';
import withRoot from './withRoot';
import UserProfile from './UserProfile';
import Paging from './Paging';

const Body = styled.div`
margin-top: -20px; 
  
`;

const UserAvatar = styled.img`
width:25px;
    height:25px;
    vertical-align: middle;
    margin-right:5px;
border-radius:50%;

`;
const UserName = styled.span`
position: relative ;
top:2px;

`;
const UserTableRow = styled(TableRow)`
&&{
    &:hover {
        background:#eee;
    }
}
`;

const TableSortLabelTheme = styled(TableSortLabel)`
color: rgb(60, 141, 188)  !important;
position:relative;
left:13px;
`;

const CustomTableCell = withStyles(theme => ({
    head: {
        color: theme.palette.common.black,
        fontSize: 14,
        padding: 4,
        textAlign: 'center',
    },
    body: {
        fontSize: 14,
        padding: 4,
        textAlign: 'center',
    },

}))(TableCell);
const styles = theme => ({
    root: {
        width: '100%',
        marginTop: theme.spacing.unit * 3,
        overflowX: 'auto',
    },
    table: {
        minWidth: 700,

    },
    row: {
        '&:nth-of-type(odd)': {
            backgroundColor: theme.palette.background.default,
        },
    },
    text_left: {
        textAlign: 'left !important',
    },
    cursor_pointer: {
        cursor: 'pointer'
    }
});

// 可扩展的排序列表
const columnData = [

    { id: 0, label: '权限排序', name: "permission" },

]

class UsersList extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            users: [],
            open: false,
            page_num: 0,
            select_page: 1,
            user: {},
            orderBy: -1,
            order: 'desc',
            anchorEl: null,
        }


        this.user_remove = this.user_remove.bind(this);
        this.UserMessageOpen = this.UserMessageOpen.bind(this);
        this.paging_request = this.paging_request.bind(this);
        this.createSortHandler = this.createSortHandler.bind(this);

    }


    componentDidMount() {

        axios.get("/user_list?current_user=" + this.props.current_user._id, {
            withCredentials: true
        })
            .then((response) => {
                return response.data;
            })
            .then(json => {

                let users = json.users


                let page_num = Math.ceil(json.user_count / 15);

                this.setState({
                    users: users,
                    page_num: page_num,


                })

                return json;
            }).catch(err => {
                console.log(err)
            })
    }

    // 删除用户
    user_remove = (ev, value) => {
        let that = this

        swal({
            title: '确定删除吗?',
            type: 'question',
            text: `你将无法恢复它!`,
            focusCancel: true,

            showCancelButton: true,
            confirmButtonText: '删除',
            confirmButtonColor: 'red',
            cancelButtonText: '朕点错了而已',
            preConfirm: () => {

                let formData = new FormData();

                formData.append('user_id', value);

                axios({
                    url: "/user_remove",
                    method: 'post',
                    data: formData,
                    withCredentials: true,
                })
                    .then(response => {
                        // console.log(response)
                        return response.data;
                    })
                    .then(json => {
                        let users = this.state.users
                        users.forEach((item, index) => {
                            if (item.user._id == value) {
                                users.splice(index, 1)
                                return
                            }
                        })
                        that.setState({
                            users: users
                        })


                        return json;
                    }).catch(err => {
                        console.log(err)
                    })
            },
            allowOutsideClick: () => !swal.isLoading()
        }).then((isConfirm) => {

            if (isConfirm.value == true) {

                swal(
                    '删除成功',
                    `此用户已经被移除`,
                    'success',
                );
            }

        }).catch((err) => {
            console.log(err)
        });

    }
    handleClick = (event, value) => {

        this.setState({
            anchorEl: event.currentTarget,
            select_user: value
        });
    };
    handleClose = () => {
        this.setState({ anchorEl: null });
    };
    operation = (ev, value) => {
        let that = this
        let select_user = this.state.select_user;
        switch (value) {

            case 1:
                this.UserMessageOpen(ev, select_user)
                break;

            case 3:
                this.user_remove(ev, select_user._id)
                break;


        }

        this.setState({ anchorEl: null });


    }
    // 用户信息打开
    UserMessageOpen(ev, user) {

        this.setState({
            open: true,
            user: user
        });

    }


    transferOpen(value) {
        this.setState({ open: value });
    }

    paging_request(select_page) {

        let encode_url = ''

        encode_url = encodeURI("/user_list?page=" + select_page + "&order=" + this.state.order + "&current_user=" + this.props.current_user._id);


        axios.get(encode_url, {
            withCredentials: true
        })
            .then((response) => {
                return response.data;
            })
            .then(json => {


                let page_num = Math.ceil(json.user_count / 15);


                window.scrollTo(0, 0);
                this.setState({
                    users: json.users,
                    page_num: page_num,
                    select_page: select_page
                })

                return json;
            }).catch(err => {
                console.log(err)
            })
    }

    createSortHandler(ev, value) {
        let order = 'desc';
        if (this.state.order === 'desc') {
            order = 'asc';
        }
        if (value != this.state.orderBy) {
            order = 'desc';

        }
        let select_page = 1

        axios.get("/user_list?order=" + order  + "&page=" + select_page + "&current_user=" + this.props.current_user._id, {
            withCredentials: true
        })
            .then((response) => {
                return response.data;
            })
            .then(json => {
                let users = json.users;


                window.scrollTo(0, 0);

                let page_num = Math.ceil(json.user_count / 15);

                this.setState({
                    users: users,
                    page_num: page_num,
                    order: order,
                    orderBy: value,
                    select_page: select_page
                })

                return json;
            }).catch(err => {
                console.log(err)
            })


    }

    transferPages(page) {

        this.paging_request(page)
    }
    transferRefresh(value) {
        if (value) {
            this.paging_request(this.state.select_page)
        }
    }

    render() {
        const { classes } = this.props,
            that = this,
            { orderBy, order, anchorEl } = this.state;
        return (
            <Body  >


                <Paper className={classes.root}>


                    <Table className={classes.table}>
                        <TableHead>
                            <TableRow>
                                <CustomTableCell>用户ID</CustomTableCell>

                                <CustomTableCell> 手机号</CustomTableCell>
                                {
                                    columnData.map((column) => {
                                        return (
                                            <CustomTableCell key={column.id} >
                                                <Tooltip
                                                    title="排序"
                                                    placement='bottom-end'
                                                    enterDelay={300}
                                                >
                                                    <TableSortLabelTheme
                                                        active={orderBy === column.name}
                                                        direction={order}
                                                        onClick={(ev) => that.createSortHandler(ev, column.name)}
                                                    >
                                                        {column.label}
                                                    </TableSortLabelTheme>
                                                </Tooltip>
                                            </CustomTableCell>
                                        )
                                    })
                                }


                                <CustomTableCell>操作</CustomTableCell>

                            </TableRow>
                        </TableHead>
                        <TableBody>
                            {this.state.users.map((n) => {

                                return (
                                    <UserTableRow key={n._id} className={classes.row}>

                                        <CustomTableCell className={classes.cursor_pointer} onClick={(ev) => that.UserMessageOpen(ev, n)} >

                                            {n.user._id}


                                        </CustomTableCell>

                                        <CustomTableCell className={classes.text_left} onClick={(ev) => that.UserMessageOpen(ev, n)}  >
                                            <UserAvatar src='/static/img/matthew.png' component='span' alt='' />
                                            <UserName>

                                                {n.user.phone}

                                            </UserName>

                                        </CustomTableCell>


                                        <CustomTableCell  >{n.permission}</CustomTableCell>

                                        <CustomTableCell  >

                                            <Button variant="contained" color="primary" onClick={(ev) => that.UserMessageOpen(ev, n)} >
                                                编辑
                                            </Button>
                                            <Button color="secondary" onClick={(ev) => this.user_remove(ev, n.user._id)}  >
                                                删除
                                            </Button>

                                        </CustomTableCell>


                                    </UserTableRow>
                                );
                            })}

                            <Menu
                                id="simple-menu"
                                anchorEl={anchorEl}
                                open={Boolean(anchorEl)}
                                onClose={this.handleClose}
                            >

                                <MenuItem onClick={(ev) => this.operation(ev, 1)} >编辑信息</MenuItem>
                                <Divider />
                                <MenuItem onClick={(ev) => this.operation(ev, 3)}  >
                                    删除
                                </MenuItem>
                            </Menu>

                        </TableBody>
                    </Table>
                    {
                        this.state.open ? <UserProfile open={this.state.open} user_profile={this.state.user} transferRefresh={value => that.transferRefresh(value)} transferOpen={open => that.transferOpen(open)} /> : <></>
                    }


                </Paper>
                <Paging page_num={this.state.page_num} select_page={this.state.select_page} transferPages={page => that.transferPages(page)} />

            </Body>
        );
    }
}
UsersList.propTypes = {
    classes: PropTypes.object.isRequired,
    // theme: PropTypes.object.isRequired,
};

export default withRoot(withStyles(styles)(UsersList));